<template>
  <el-card shadow="hover" class="mt-10">
    <template #header>
      <div>分类销售排行</div>
    </template>

    <Chart height="300px" :option="chartOption" />
  </el-card>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import type { ECOption } from "@/utils/echarts";

defineOptions({
  name: "CategoryRank",
});

const props = defineProps<{
  data: any;
}>();

const chartOption = ref<ECOption>({
  title: [
    {
      text: "品类分布",
    },
    {
      text: "累计订单量",
      textStyle: {
        fontSize: 14,
        color: "#999",
      },
      subtext: "0",
      subtextStyle: {
        fontSize: 25,
      },
      left: "center",
      top: "43%",
    },
  ],
  series: {
    type: "pie",
    data: [],
    radius: ["45%", "70%"],
    itemStyle: {
      borderWidth: 2,
      borderColor: "#fff",
    },
  },
  legend: {
    top: "middle",
    right: 40,
    orient: "vertical",
    formatter: function (name) {
      const data = (chartOption.value.series as any).data as any;

      const total = data.reduce((p: number, c: any) => {
        return p + c.value;
      }, 0);

      const value = data.find((item: any) => item.name === name).value;

      const percent = ((value / total) * 100).toFixed(2) + "%";

      return name + " | " + percent;
    },
  },
});

watch(props, (props) => {
  const data = props.data.category.axisX.map((name: string, index: number) => {
    return {
      name,
      value: props.data.category.data1[index],
    };
  });
  const total = data.reduce((p: number, c: any) => {
    return p + c.value;
  }, 0);
  (chartOption.value.series as any).data = data;
  (chartOption.value.title as any)[1].subtext = total;
});
</script>

<style scoped lang="scss">
.mt-10 {
  margin-top: 10px;
}
</style>
